package com.dzx.currentency.aqs;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月20日 14:49:27
 */

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * ForkJoinTask的 使用
 */
public class ForkJoinExample extends RecursiveTask<Integer> {

    private final int should = 5; //阀值

    private int start;

    private int end;

    public ForkJoinExample(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean flag = (end - start) <= should; // 判断start 和 end 的差是否小于 阀值
        if (flag) {    //如果 小于阀值 不进行切分
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {       //如果 大于阀值则进行切分成子任务
            int middle = (end + start) / 2;
            ForkJoinExample forkJoinExample1 = new ForkJoinExample(start, middle);
            ForkJoinExample forkJoinExample2 = new ForkJoinExample(middle + 1, end);
            //执行子任务
            forkJoinExample1.fork();
            forkJoinExample2.fork();
            //合并子任务
            int A = forkJoinExample1.join();
            int B = forkJoinExample2.join();
            sum = A + B;
        }
        return sum;
    }


    public static void main(String[] args) {
        try {
            ForkJoinPool forkJoinPool = new ForkJoinPool(); //ForkJoinPool
            ForkJoinExample forkJoinExample = new ForkJoinExample(1, 100);
            ForkJoinTask result = forkJoinPool.submit(forkJoinExample);
            System.out.println(result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
